<?php

/**
 * Subclass for representing a row from the 'mail_task' table.
 *
 * 
 *
 * @package lib.model
 */ 
class MailTask extends BaseMailTask
{
	const PRIORITY_LOW         = 1;
	const PRIORITY_NORMAL      = 2;
	const PRIORITY_HIGH        = 3;
	const LIMIT_SENDING_MAILS_PER_TIME = 10;
	/**
	 * 
	 * returns array of priorities with translation
	 */
	public static function getPriorityList()
	{
		return $priorities = array(self::PRIORITY_LOW => sfContext::getInstance()->getI18N()->__('low')
		                  , self::PRIORITY_NORMAL => sfContext::getInstance()->getI18N()->__('normal')
		                  , self::PRIORITY_HIGH => sfContext::getInstance()->getI18N()->__('high')
		                  );
	}
	/**
	 * 
	 * create new mailtask and save it in db, returns true on success
	 * @param int $userId
	 * @param int $priority
	 * @param string $subject
	 * @param mail $mailto
	 * @param string $title
	 * @param string $body
	 * @param  $sender
	 * @param mail $mailfrom
	 * @param timestamp $startAtTm
	 * @throws Exception if mails invalid
	 */
	public static function createNew($userId, $priority, $subject, $mailto, $title, $body, $sender, $mailfrom, $startAtTm = 0)
	{
		$mailTask = new MailTask();
		$mailTask->setUserId($userId);
		$mailTask->setStatusId(MyConstants::STATUS_NEW);
		$mailTask->setPriority($priority);
		//TODO: if recipient_id is set, get e-mail ($mailto) from user table
		$mailTask->setSubject($subject);
		$mailTask->setMailto($mailto);
		$mailTask->setTitle($title);
        $mailTask->setBody($body);
        $mailTask->setSender($sender);
        $mailTask->setMailfrom($mailfrom);
        //$mailTask->setStartAt($start_at == 0 ? time(): $start_at);
        if( !(self::validateTask($mailTask)) )
        {
        	throw new Exception('Mail task not valid!');
        }
        // setSentAt() must by set when mail will be sended, $start_at = time()
        $mailTask->save();
        return true;
	}
	/**
	 * 
	 * task validation 
	 * @param obj $task
	 */
	public static function validateTask($task)
	{
		/* @var $task MailTask */
		/* @var $validator sfEmailValidator */
		$validator = new sfEmailValidator();
		$emailfrom = $task->getMailfrom();
		$mailto = $task->getMailto();
		$validator->initialize(sfContext::getInstance()
		                      , array('strict' => true
		                              , 'email_error' => 'This E-mail is invalid.'));
		if( !($res = $validator->execute($emailfrom, $email_error)) )
		{
			return false;
		}
		if( !($res1 = $validator->execute($mailto, $email_error)) )
		{
			return false;
		}
        return true;
	}
}
